package com.fitness.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.anji.captcha.model.common.RepCodeEnum;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fitness.front.enums.VerificationEnum;
import com.fitness.front.exception.BizException;
import com.fitness.front.modal.member.dto.LoginFormDto;
import com.fitness.front.modal.member.dto.RegisterFormDto;
import com.fitness.front.modal.member.entity.Member;
import com.fitness.front.modal.response.ServerResponseEntity;
import com.fitness.front.service.IMemberService;
import com.fitness.front.service.VerificationService;
import com.fitness.front.utils.EncryptUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/front/auth")
@Slf4j
public class AuthController {

    @Autowired
    private CaptchaService captchaService;
    private final IMemberService memberService;
    private final VerificationService verificationService;

    @PostMapping( "/captcha/get" )
    public ResponseModel get(@RequestBody CaptchaVO captchaVO) {
        return captchaService.get(captchaVO);
    }

    @PostMapping( "/captcha/check" )
    public ResponseModel check(@RequestBody CaptchaVO captchaVO) {
        ResponseModel responseModel;
        try {
            responseModel = captchaService.check(captchaVO);
        }catch (Exception e) {
            return ResponseModel.errorMsg(RepCodeEnum.API_CAPTCHA_COORDINATE_ERROR);
        }
        return responseModel;
    }

    @PostMapping("/login")
    public ServerResponseEntity<?> login(@RequestBody LoginFormDto loginFormDto){
        ResponseModel responseModel = captchaService.verification(loginFormDto.getCaptchaVO());
        if(!responseModel.isSuccess()){
            return ServerResponseEntity.fail(HttpStatus.NOT_ACCEPTABLE.value()+"","验证码校验失败");
        }
        String username = loginFormDto.getUsername();
        String password = loginFormDto.getPassword();

        //校验用户是否存在
        Member member = memberService.getOne(new LambdaQueryWrapper<Member>().eq(Member::getUsername,username));
        if(member == null){
            return ServerResponseEntity.fail(HttpStatus.NOT_ACCEPTABLE.value()+"","用户不存在" );
        }
        if(!EncryptUtil.matchPassword(password,member.getSalt(),member.getPassword())){
            return ServerResponseEntity.fail(HttpStatus.NOT_ACCEPTABLE.value()+"","用户名密码错误" );
        }
        StpUtil.login(member.getId()+"_"+username);
        String token = StpUtil.getTokenInfo().getTokenValue();
        return ServerResponseEntity.success(token);
    }

    @PostMapping("/register")
    public ServerResponseEntity<?> register(@Valid @RequestBody RegisterFormDto registerFormDto) {
//        ResponseModel responseModel = captchaService.verification(registerFormDto.getCaptchaVO());
//        if(!responseModel.isSuccess()){
//            return ServerResponseEntity.fail(HttpStatus.NOT_ACCEPTABLE.value()+"","验证码校验失败");
//        }

        boolean result = memberService.register(registerFormDto);
        return ServerResponseEntity.success(result);
    }

    @PostMapping("/resetByMobile")
    public ServerResponseEntity<Member> resetByMobile(@NotNull(message = "手机号为空") @RequestParam String mobile,
                                                      @NotNull(message = "验证码为空") @RequestParam String code,
                                                      @RequestHeader String uuid) {
        //校验短信验证码是否正确
        if (verificationService.verifyPhoneCode(code,mobile, VerificationEnum.FIND_USER)) {
            //校验是否通过手机号可获取会员,存在则将会员信息存入缓存，有效时间3分钟
            memberService.findByMobile(uuid, mobile);
            return ServerResponseEntity.success();
        } else {
            throw new BizException("用户不存在");
        }
    }

    @PostMapping("/resetPassword")
    public ServerResponseEntity<Boolean> resetByMobile(@NotNull(message = "密码为空") @RequestParam String password,
                                                       @RequestHeader String uuid) {

        return ServerResponseEntity.success(memberService.resetByMobile(uuid, password));
    }

    @SaCheckLogin
    @PostMapping("/logout")
    public ServerResponseEntity<?> logout() {
        this.memberService.logout();
        return ServerResponseEntity.success();
    }
}
